<template>
  <view class="overall">
    <view class="content">
      <!-- 日历 -->
      <view style="background-color: white;margin-top: -80px;" class="calendar" @touchstart="handleTouchStart"
        @touchend="handleTouchEnd">
        <view class="header"></view>
        <view class="days-of-week">
          <view v-for="day in daysOfWeek" :key="day">{{ day }}</view>
        </view>
        <view class="dates">
          <view v-for="(date, index) in dates" :key="index"
            :class="{ 'not-current-month': date.month !== month, 'today': date.isToday }"
            :style="date.day == myday ? 'background-color:#A6A6A6;' : ''" @click="checked(date.day)">
            <view>{{ date.day }}</view>
          </view>
        </view>
      </view>
      
      <wd-status-tip image-size="60" v-if="doctor == null" image="content" tip="暂无内容" />
      
      <view class="tiem" v-if="doctor != null">
        <view v-for="(item, index) in office" :key="index" class="doctor-item">
          <view style="background-color: white;margin-top: 10px; height: 130px;">
            <view class="doctor">
              <view>
                <image :src="'https://yiliao.kuxia.top/' + item.doctor.avatar" mode=""></image>
              </view>
              <view>
                <view>
                  <view>{{ item.doctor.name }}</view>
                  <view>{{ item.doctor.duties }}</view>
                </view>
                <view>
                  {{ item.doctor.good }}
                </view>
              </view>
            </view>
            
            <wd-status-tip image-size="60" v-if="item.office == null" image="content" tip="暂无内容" />
            
            <view class="list" v-if="item.office != null && Array.isArray(item.office)">
              <view v-for="(items, index) in item.office.sort((a, b) => a.time - b.time)" :key="index"
                :class="items.num >= items.source ? 'notLeft' : 'leftover'">
                <view>
                  <view>{{ items.date }}</view>
                  <view>
                    {{ new Date(items.date).getDay() === 0 ? '（周日）' :
                    new Date(items.date).getDay() === 1 ? '（周一）' :
                    new Date(items.date).getDay() === 2 ? '（周二）' :
                    new Date(items.date).getDay() === 3 ? '（周三）' :
                    new Date(items.date).getDay() === 4 ? '（周四）' :
                    new Date(items.date).getDay() === 5 ? '（周五）' :
                    new Date(items.date).getDay() === 6 ? '（周六）' : '' }}
                  </view>
                  <view v-if="items.time === 1">上午</view>
                  <view v-if="items.time === 2">下午</view>
                </view>

                <view v-if="items.num >= items.source ? false : true">
                  <view style="margin-top: -26%;margin-left: -30px;">￥ {{ item.doctor.money }}</view>
                  <view style="margin-top: -7%;position: absolute;right: 5%;"
                    @click="handleBooking(item, items)">预约</view>
                </view>

                <view v-if="items.num >= items.source">
                  <view>约满</view>
                </view>
              </view>
            </view>
          </view>
          
          <!-- 医生项底部的分隔线 -->
          <view v-if="index < office.length - 1" class="divider"></view>
        </view>
      </view>
    </view>
  </view>
</template>

<script lang="ts" setup>
import { computed, onMounted, ref, watch } from 'vue';

// 响应式数据
const contentList = ref([]); // 用于内容展示
const doctor = ref([]);  // 医生信息
const office = ref([]);   // 医生办公信息
const name = ref<any>(null);  // 科室信息
const topHeight = ref(0);  // 用于存储动态计算的top高度
const availableNumbers = ref({}); // 存储每个医生的可用号源数量

// 在组件挂载时获取设备信息
onMounted(() => {
  const systemInfo = uni.getSystemInfoSync();
  const navBarHeight = systemInfo.statusBarHeight;  // 获取状态栏的高度
  topHeight.value = navBarHeight + 44;  // 导航栏高度加50px
  console.log('导航栏高度:', navBarHeight);
  console.log('动态计算的top高度:', topHeight.value);
});

// 获取科室数据
uni.getStorage({
  key: 'selectedDepartment',
  success: (res) => {
    console.log('读取存储数据:', res.data);
    name.value = res.data; // 将科室数据赋值给name
  },
  fail: (err) => {
    console.error('读取存储失败', err);
  }
});

// 请求医生信息
async function fetchDoctorData(departmentId : number) {
  try {
    const response = await uni.request({
      url: 'https://yiliao.kuxia.top/app/doctor/index',  // 替换为实际医生数据接口
      method: 'POST',
      data: {
        depart_id: departmentId // 使用从存储中读取的departmentId
      },
    });

    console.log('医生信息接口响应数据:', response.data);

    if (response.data && response.data.data) {
      doctor.value = response.data.data;

      const newmonth = (month.value + 1).toString().padStart(2, '0'); // 月份从 0 开始，需要加 1，并补齐两位
      const newday = day.value.toString().padStart(2, '0'); // 补齐两位
      const formattedDate = `${year.value}-${newmonth}-${newday}`;
      console.log('格式化后的日期:', formattedDate);

      if (response.data.data != null) {
        const mergedArray = await Promise.all(
          response.data.data.map(async (item) => {
            const schedulingResponse = await uni.request({
              url: 'https://yiliao.kuxia.top/app/scheduling/index',
              method: 'POST',
              data: {
                depart_id: item.depart_id,
                date: formattedDate,
              },
            });

            let officeData = schedulingResponse.data;

            if (Array.isArray(officeData)) {
              officeData.sort((a, b) => a.time - b.time);
            } else {
              console.error('办公室数据不是数组:', officeData);
              officeData = [officeData];
            }

            // 请求可用号源数量
            fetchAvailableNumbers(item.id);
            
            return {
              doctor: item,
              office: officeData,
            };
          })
        );

        office.value = mergedArray;
        console.log('合并后的医生和办公信息:', mergedArray);
      }
    } else {
      console.error("医生信息数据不完整或错误");
    }
  } catch (error) {
    console.error('获取医生信息失败:', error);
  }
}

// 获取可用号源数量
async function fetchAvailableNumbers(doctorId: number) {
  try {
    const response = await uni.request({
      url: 'https://yiliao.kuxia.top/app/Doctor/details',
      method: 'POST',
      data: {
        doctor_id: doctorId
      }
    });
    
    console.log(`医生ID=${doctorId}的可用号源响应数据:`, response.data);
    
    if (response.data && response.data.data && response.data.data.children) {
      availableNumbers.value = {
        ...availableNumbers.value,
        [doctorId]: response.data.data.children.length
      };
    }
  } catch (error) {
    console.error(`获取医生ID=${doctorId}的可用号源失败:`, error);
  }
}

// 监听日期选择变化，重新请求数据
watch(myday, () => {
  if (name.value && name.value.id) {
    fetchDoctorData(name.value.id);
  }
});

// 初始化事件，获取并加载科室和医生信息
async function event() {
  uni.getStorage({
    key: 'selectedDepartment',
    success: function (res) {
      console.log(res.data);
      name.value = res.data; // 获取存储的科室信息
      fetchDoctorData(res.data.id); // 使用存储的id获取医生数据
    }
  });
}

event();

// 日历相关
const year = ref(new Date().getFullYear());
const month = ref(new Date().getMonth());
const daysOfWeek = ['日', '一', '二', '三', '四', '五', '六'];
const day = ref(new Date().getDate());
const myday = ref(null);

const dates = computed(() => {
  const today = new Date().getDate();
  const firstDayOfMonth = new Date(year.value, month.value, 1).getDay();
  const totalDaysInMonth = new Date(year.value, month.value + 1, 0).getDate();
  const datesArray = [];
  for (let i = 1; i <= totalDaysInMonth; i++) {
    const isToday = i === today && month.value === new Date().getMonth();
    datesArray.push({ day: i, month: month.value, isToday });
  }
  return datesArray;
});

const checked = (day) => {
  const today = new Date();
  const selectedDate = new Date(year.value, month.value, day); // 用户点击的日期

  // 如果选中的日期是过去的日期
  if (selectedDate < today) {
    uni.showToast({
      title: '无法选择过去的日期',
      icon: 'none',
      duration: 2000
    });
  } else {
    myday.value = day; // 选择日期
  }
};

// 返回上一页
const returns = () => {
  console.log('返回上一页');
}

// 处理预约逻辑
const handleBooking = (doctorItem, scheduleItem) => {
  if (doctorItem.doctor.name === '郑婉晴') {
    navigateToBookingPage(doctorItem, scheduleItem);
  } else {
    uni.showToast({
      title: '当前医生不可预约',
      icon: 'none',
      duration: 2000
    });
  }
}

// 跳转到预约页面
const navigateToBookingPage = (doctorItem, scheduleItem) => {
  const bookingData = {
    doctor: doctorItem.doctor,
    schedule: scheduleItem,
    availableNumber: availableNumbers.value[doctorItem.doctor.id] || 0
  };
  uni.setStorageSync('bookingData', JSON.stringify(bookingData)); // 保存选中的医生和排班信息
  console.log('Stored Booking Data:', bookingData);
  uni.navigateTo({
    url: `/pages/sure/sure`
  });
};
</script>

<style scoped>
	.overall {
		width: 100%;
		padding-bottom: 30vh;
	}

	.title {
		width: 100%;
		height: 5rem;
		background-color: #00DACA;
		color: white;
		display: flex;
		align-items: center;
		position: fixed;
		top: 0;
	}

	.name {
		display: flex;
		align-items: center;
		font-weight: bold;
		font-size: 42rpx;
		line-height: 3rem;
		margin-left: 3%;
		margin-top: 30px;
	}

	.name>view {
		margin-left: 30rpx;
	}

	.content {
		width: 94%;
		margin: 180rpx 3%;
	}

	.calendar {
		min-height: 35vh;
		border-bottom: #EBEBEB 6rpx solid;
	}

	.days-of-week {
		width: 100%;
		display: flex;
		border-bottom: #EBEBEB 5rpx solid;
	}

	.days-of-week>view {
		width: 92rpx;
		height: 60rpx;
		margin: 5rpx 7rpx;
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.dates {
		width: 100%;
		display: flex;
		flex-wrap: wrap;
	}

	.dates>view {
		width: 12.5%;
		height: 70rpx;
		display: flex;
		justify-content: center;
		align-items: center;
		margin: 4rpx 7rpx;
	}

	.today {
		color: #00DACA;
	}

	.tiem {
		width: 100%;
	}

	.doctor-item {
		margin-bottom: 20rpx; /* 增加项与分隔线之间的间距 */
	}

	.doctor image {
		width: 100%;
		height: 100%;
		object-fit: cover;
		border-radius: 50%;
	}

	.doctor {
		width: 100%;
		height: 140rpx;
		display: flex;
		justify-content: center;
		padding-top: 30rpx;
		background-color: white;
	}

	.doctor>view:first-child {
		width: 100rpx;
		height: 100rpx;
		background-color: #E5E5E5;
		display: flex;
		justify-content: center;
		align-items: center;
		border-radius: 10000rpx;
	}

	.doctor>view:last-child>view:first-child {
		display: flex;
		margin-bottom: 15rpx;
	}

	.doctor>view:last-child {
		width: 72%;
		margin-left: 5%;
		font-size: 28rpx;
	}

	.doctor>view:last-child>view:first-child>view:first-child {
		font-weight: bold;
		padding-right: 40rpx;
	}

	.doctor>view:last-child>view:first-child>view:last-child {
		border-left: 5rpx #EEEEEE solid;
		padding-left: 20rpx;
		color: #A6A6A6;
	}

	.doctor>view:last-child>view:last-child {
		width: 90%;
		font-size: 28rpx;
		color: #A6A6A6;
		word-wrap: break-word;
	}

	.list {
		width: 100%;
		margin-top: 10rpx;
		font-size: 28rpx;
	}

	.list>view {
		border-bottom: #EBEBEB 6rpx solid;
		display: flex;
		height: 130rpx;
		justify-content: space-between;
	}

	.list>view>view {
		display: flex;
		min-width: 35%;
		justify-content: space-between;
		align-items: center;
	}

	.notLeft {
		color: #A6A6A6;
	}

	.leftover>view:first-child {
		color: #00DACA;
	}

	.leftover>view:last-child>view:first-child {
		color: #EC5C28;
		margin-right: 30rpx;
	}

	.leftover>view:last-child>view:last-child {
		background-color: #2EC7C9;
		color: white;
		width: 100rpx;
		padding: 10rpx 5rpx;
		border-radius: 10rpx;
		white-space: nowrap;
		text-align: center;
	}

	.name>image {
		width: 20px;
		height: 20px;
	}

/* 分隔线样式 */
.divider {
  height: 1px;
  background-color: #E5E5E5;
  margin: 10px 0;
  width: 100%;
}
</style>
    